import { useCallback, useMemo, useState } from 'react';
import type { ActionType } from '@ant-design/pro-components';
import { createCrudService } from '@/services/crudService';
import { checkRequiredFields } from '@/components/utils/index';
import type { CrudConfig, SearchFieldConfig } from '../types';

/**
 * 处理数据加载和搜索相关逻辑
 */
export function usePageTemplateData<T extends Record<string, any>>(
  crudConfig?: CrudConfig,
  searchFields?: SearchFieldConfig[],
  searchInitialValues?: Record<string, any>,
  onSearch?: (values: Record<string, any>) => void,
  onReset?: () => void,
) {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<T[]>([]);
  const [total, setTotal] = useState(0);
  const [searchParams, setSearchParams] = useState(searchInitialValues || {});

  // CRUD服务
  const crudService = useMemo(() => {
    return crudConfig ? createCrudService<T>(crudConfig) : null;
  }, [crudConfig]);

  // 加载数据
  const loadData = useCallback(
    async (params?: any) => {
      if (!crudService) return { data: [], total: 0, success: false };

      const finalParams = { ...searchParams, ...params };

      if (!checkRequiredFields(searchFields, finalParams)) {
        return { data: [], total: 0, success: false };
      }

      setLoading(true);
      try {
        const result = await crudService.list(finalParams);
        setDataSource(result.data || []);
        setTotal(result.total || 0);
        return {
          data: result.data || [],
          total: result.total || 0,
          success: true,
        };
      } catch (error) {
        return { data: [], total: 0, success: false };
      } finally {
        setLoading(false);
      }
    },
    [crudService, searchParams, searchFields],
  );

  // 搜索处理
  const handleSearch = useCallback(
    (values: Record<string, any>, actionRef?: React.MutableRefObject<ActionType | undefined>) => {
      setSearchParams(values);
      if (onSearch) {
        onSearch(values);
      } else {
        actionRef?.current?.reload();
      }
    },
    [onSearch],
  );

  // 重置处理
  const handleReset = useCallback(
    (actionRef?: React.MutableRefObject<ActionType | undefined>) => {
      setSearchParams({});
      if (onReset) {
        onReset();
      } else {
        actionRef?.current?.reload();
      }
    },
    [onReset],
  );

  return {
    loading,
    dataSource,
    total,
    searchParams,
    crudService,
    loadData,
    handleSearch,
    handleReset,
  };
}

